package com.fare.taluo.auth.security;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.openkoala.auth.application.RoleApplication;
import org.openkoala.auth.application.UserApplication;
import org.openkoala.auth.application.vo.RoleVO;
import org.openkoala.auth.application.vo.UserVO;
import org.openkoala.koala.auth.ss3adapter.CustomUserDetails;
import org.springframework.security.core.context.SecurityContextHolder;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.auth.domain.UserInfoEntity;
import com.fare.taluo.auth.domain.repository.IUserInfoRepository;
/**
 * 登陆帐号上下文，通过该类的静态方法<code>getLoginUser</code>可以获得当前登陆的用户信息
 * <p>这些信息包括，当前登陆用户的帐号名，表中ID，角色ID,角色名称，所属航空公司或渠道KEY
 * @author xiangsf 2014-04-30
 *
 */
public class ContextLoginUser {
	
	public final static String CURRENT_USER_INSESSION = "currentUser";
	/**
	 * 获得当前用户
	 * @return
	 */
	public static LogonUserCertificate getLoginUser(){
		LogonUserCertificate currentUser = null;
		if(getSession()!=null){
			if(getSession().getAttribute(CURRENT_USER_INSESSION)!=null){
				 currentUser = (LogonUserCertificate)getSession().getAttribute(CURRENT_USER_INSESSION);
			}else{
				CustomUserDetails current = (CustomUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
				String username = current.getUsername(); 
				UserVO userVO = InstanceFactory.getInstance(UserApplication.class).findByUserAccount(username);
				UserInfoEntity userinfo = InstanceFactory.getInstance(IUserInfoRepository.class).getUserInfoByLogonid(username);
				//目前一个帐号只有一个角色，所以取默认的第一个
				List<RoleVO> roleVOs = InstanceFactory.getInstance(RoleApplication.class).findRoleByUserAccount(username);
				RoleVO roleVO = roleVOs != null && !roleVOs.isEmpty() ? roleVOs.get(0) : null;
			
				currentUser = new LogonUserCertificate(username, userinfo.getId(),userVO.getId(),
						userinfo.getName());
				if(roleVO != null){
					currentUser.setRoleId(roleVO.getId());
					currentUser.setRoleName(roleVO.getName());
				}
				if(userinfo != null){
					currentUser.setSourceId(userinfo.getSourceId());
					currentUser.setSourceName(userinfo.getSourceName());
					currentUser.setSourceKey(userinfo.getSourceKey());
				}
				getSession().setAttribute(CURRENT_USER_INSESSION, currentUser);
			}
		}
		return currentUser;
	}
	/**
	 * 得到request对象
	 * @return  request
	 */
	public static HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	/**
	 * 得到Session对象
	 * @return Session
	 */
	public static HttpSession getSession() {
		return getRequest().getSession();
	}
}
